package com.example.finger.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.finger.FingerHelper;
import com.example.finger.R;
import com.example.finger.SerialPortUtil;
import com.example.finger.bean.LockLog;
import com.example.finger.bean.PadLock;
import com.example.finger.bean.TaskSheet;
import com.example.finger.bean.TaskWithPadlock;
import com.example.finger.dialog.ChangePwdDialog;
import com.example.finger.dialog.FingerDialog;
import com.example.finger.fragment.LogFragment;
import com.example.finger.fragment.TaskFragment;
import com.example.finger.fragment.TemporaryTaskFragment;
import com.example.finger.socket.SoketService;
import com.example.finger.rules.FingerLib;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lyxmaster.lib.LazyViewPager.LazyFragmentPagerAdapter;
import com.lyxmaster.lib.LazyViewPager.LazyViewPager;
import com.lyxmaster.lib.ahbottomnavigation.AHBottomNavigation;
import com.lyxmaster.lib.ahbottomnavigation.AHBottomNavigationItem;
import com.lyxmaster.lib.toasty.Toasty;
import com.lyxmaster.lib.util.DataConfig;
import com.lyxmaster.lib.util.FileUtils;
import com.lyxmaster.lib.view.BaseV4Fragment;
import com.lyxmaster.lib.xutils.ex.DbException;
import com.lyxmaster.lib.xutils.view.annotation.ContentView;
import com.lyxmaster.lib.xutils.view.annotation.ViewInject;
import com.lyxmaster.lib.xutils.x;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by LYX on 2018/11/14.
 */
@ContentView(R.layout.activity_main)
public class MainActivity extends MyBaseActivity {
    @ViewInject(R.id.spinner)
    private Spinner spinner;
    @ViewInject(R.id.imageview)
    private ImageView imageView;
    @ViewInject(R.id.tv_result)
    private TextView textViewResult;
    @ViewInject(R.id.viewpager)
    private LazyViewPager viewPager;
    @ViewInject(R.id.bottom_navigation)
    private AHBottomNavigation bottomNavigation;

    private List<BaseV4Fragment> baseV4FragmentList = new ArrayList<>();
    private TaskFragment taskFragment = new TaskFragment();
    //    private TemporaryTaskFragment temporaryTaskFragment = new TemporaryTaskFragment();
    private LogFragment logFragment = new LogFragment();
    Intent intentSocket;

    private FingerLib m_szHost;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        bFinishTwice = true;

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        //启动socket服务
        intentSocket = new Intent(this, SoketService.class);
        startService(intentSocket);

        FingerHelper.getInStance().initDb();

        setTitle("任务单");
        FingerHelper.getInStance().TASTDIR = getApplicationContext().getFilesDir().getAbsolutePath();

        FingerHelper.getInStance().m_szHost = new FingerLib(this, textViewResult, imageView, runEnableCtrl, spinner);
        m_szHost = FingerHelper.getInStance().m_szHost;
        hud.show();
        hud.setLabel("正在初始化");
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                FingerHelper.getInStance().initDb();
                SerialPortUtil.getInstance().OpenPower();
                FingerHelper.getInStance().taskWithPadlocks = new Gson().fromJson(FileUtils.getFileContent(new File(FingerHelper.TASTDIR + FingerHelper.TASKPATH)), TaskWithPadlock.class);
                TaskWithPadlock as = FingerHelper.getInStance().taskWithPadlocks;
                if (FingerHelper.getInStance().taskWithPadlocks != null) {
                    try {
                        //写入挂锁
                        FingerHelper.getInStance().dbManager.replace(FingerHelper.getInStance().taskWithPadlocks.getPadLcok());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //开锁任务
                    FingerHelper.getInStance().taskSheetList = FingerHelper.getInStance().taskWithPadlocks.getList();
                }
                if (FingerHelper.getInStance().taskSheetList == null)
                    FingerHelper.getInStance().taskSheetList = new ArrayList<>();
                FingerHelper.getInStance().initDevId(context);


                ((Activity) (context)).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (m_szHost.OpenDevice("/dev/ttyMT3", 115200) == 0) {
//                            Toasty.success(context, "指纹模块启动成功").show();
                            initFragment();
                            SerialPortUtil.getInstance().openSerialPort(context);
                        } else {
                            Toasty.error(context, "指纹模块启动失败").show();
                        }
                        hud.dismiss();
                    }
                });
            }
        }, 200);
    }

    private void initFragment() {
        bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);
        bottomNavigation.addItem(new AHBottomNavigationItem(getString(R.string.tab_1), R.drawable.task0));
//        bottomNavigation.addItem(new AHBottomNavigationItem(getString(R.string.tab_2), R.drawable.task1));
        bottomNavigation.addItem(new AHBottomNavigationItem(getString(R.string.tab_3), R.drawable.log));
        bottomNavigation.setOnTabSelectedListener(onTabSelectedListener);
        bottomNavigation.setAccentColor(getResources().getColor(R.color.main));
        bottomNavigation.setInactiveColor(getResources().getColor(R.color.category_name_gray));

        baseV4FragmentList.add(taskFragment);
//        baseV4FragmentList.add(temporaryTaskFragment);
        baseV4FragmentList.add(logFragment);
        viewPager.isScrollable = true;
        viewPager.setAdapter(new LazyFragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            protected Fragment getItem(ViewGroup container, int position) {
                return baseV4FragmentList.get(position);
            }

            @Override
            public int getCount() {
                return baseV4FragmentList.size();
            }
        });

        viewPager.setCurrentItem(0);

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        setTitle(getString(R.string.tab_1));
                        break;
//                    case 1:
//                        setTitle(getString(R.string.tab_2));
//                        break;
                    case 1:
                        setTitle(getString(R.string.tab_3));
                        logFragment.upDate();
                        break;
                }
                bottomNavigation.setCurrentItem(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private AHBottomNavigation.OnTabSelectedListener onTabSelectedListener = new AHBottomNavigation.OnTabSelectedListener() {
        @Override
        public boolean onTabSelected(int position, boolean wasSelected) {
            viewPager.setCurrentItem(position);
            return true;
        }
    };

    @Override
    public void onDestroy() {
        try {
            super.onDestroy();
            System.exit(0);
        } catch (Exception e) {

        }

    }

    Runnable runEnableCtrl = new Runnable() {
        public void run() {

        }
    };

    @Override
    public void onResume() {
        super.onResume();

        PowerControl(1);
        SerialPortUtil.getInstance().OpenPower();
    }

    @Override
    public void onPause() {
        super.onPause();

        long dateNow = new Date().getTime();

        if (FingerHelper.getInStance().taskSheetList != null) {
            for (TaskSheet taskSheet : FingerHelper.getInStance().taskSheetList) {
                long dataStart = DataConfig.strToDateLong(taskSheet.getTask().getTimestart()).getTime();
                long dataEnd = DataConfig.strToDateLong(taskSheet.getTask().getTimeend()).getTime();
                if (dateNow < dataStart || dateNow > dataEnd) {
                    taskSheet.getTask().setTimeStatust(-100);
                }
            }

            FileUtils.writeTxtToFile(new Gson().toJson(FingerHelper.getInStance().taskWithPadlocks).toString(), FingerHelper.TASTDIR, FingerHelper.TASKPATH);
        }

        PowerControl(0);
        SerialPortUtil.getInstance().ClosePower();
    }

    String RFID_POWER_PATH = "/proc/gpiocontrol/set_id";

    public void PowerControl(int state) {
        if (state == 0 || state == 1) {
            try {
                FileWriter localFileWriterOn = new FileWriter(new File(RFID_POWER_PATH));
                if (state == 1) {
                    localFileWriterOn.write("1");
                } else if (state == 0) {
                    localFileWriterOn.write("0");
                }
                localFileWriterOn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    //当用户点击Action按钮的时候，系统会调用Activity的onOptionsItemSelected()方法
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_add:
                startActivityForResult(new Intent(activity, AddTaskActivity.class), 0);
                return true;
            case R.id.menu_pwd:
//                startActivityForResult(new Intent(activity, ChangPwdActivity.class), 0);
                try {
                    List<String> FingerData = new Gson().fromJson(FileUtils.getFileContent(new File(FingerHelper.TASTDIR + FingerHelper.MANAFIGER)), new TypeToken<List<String>>() {
                    }.getType());
                    if (FingerData == null || FingerData.size() == 0) {
                        return true;
                    }
                } catch (Exception e) {
                    return true;
                }

                ChangePwdDialog fingerDialog = ChangePwdDialog.getInstance("");
                fingerDialog.show(getSupportFragmentManager(), "fs");
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
